package top.bulk.delay.mapper;

import cn.hutool.core.collection.ListUtil;
import org.springframework.stereotype.Component;
import top.bulk.delay.entity.OrderEntity;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * mapper 正常是查询数据库，这里直接从内存中查询了
 *
 * @author 散装java
 * @date 2024-08-13
 */
@Component
public class OrderMapper {
    // 模拟数据，假装是存储在数据库中的
    public static final List<OrderEntity> ORDER_ENTITY_LIST = ListUtil.toList(
            new OrderEntity(1, "order-1", 1, 1, LocalDateTime.now(), LocalDateTime.now()),
            new OrderEntity(2, "order-2", 1, 1, LocalDateTime.now(), LocalDateTime.now()),
            new OrderEntity(3, "order-3", 1, 1, LocalDateTime.now().minusMinutes(15), LocalDateTime.now())
    );

    /**
     * 根据id 查询订单
     *
     * @param id id
     * @return order
     */
    public OrderEntity queryById(Integer id) {
        return ORDER_ENTITY_LIST.stream()
                .filter(orderEntity -> orderEntity.getId().equals(id))
                .findFirst()
                .orElse(null);
    }

    /**
     * 根据id 更新状态
     */
    public void closeOrder(Integer id) {
        // 这里如果是实际业务场景，注意现成安全问题
        ORDER_ENTITY_LIST.stream()
                .filter(orderEntity -> orderEntity.getId().equals(id))
                .findFirst()
                .ifPresent(orderEntity -> {
                    orderEntity.setStatus(5);
                    orderEntity.setUpdateTime(LocalDateTime.now());
                });
    }

    public void add(OrderEntity orderEntity) {
        LocalDateTime now = LocalDateTime.now();
        orderEntity.setAddTime(now);
        orderEntity.setUpdateTime(now);
        orderEntity.setId(ORDER_ENTITY_LIST.size() + 1);
        ORDER_ENTITY_LIST.add(orderEntity);
    }

    public List<OrderEntity> queryAll() {
        return ORDER_ENTITY_LIST;
    }

    public void printAll() {
        ORDER_ENTITY_LIST.forEach(System.out::println);
    }

    public List<OrderEntity> queryCloseByTime(LocalDateTime time, Integer limit) {
        // 查询状态为1，且创建时间小于 time 的订单，限制 limit 条
        return ORDER_ENTITY_LIST.stream()
                .filter(orderEntity -> orderEntity.getStatus().equals(1))
                .filter(orderEntity -> orderEntity.getAddTime().isBefore(time))
                .limit(limit)
                .collect(Collectors.toList());
    }
}
